#Aika MS3 parser

import os, sys
from Sanae3D.lib.ModelObject import Model3D
from Sanae3D.lib.StructReader import StructReader

class AikaOnline_ms3(Model3D):
    
    def __init__(self, obj3D=None, outFile=None, inFile=None):
        
        super(AikaOnline_ms3,self).__init__("MS3")
        self.obj3D = obj3D
        self.inFile = inFile
        self.outFile = outFile
        
    def parse_faces(self, numFaces, meshName):
        
        for i in range(numFaces):
            v1, v2, v3 = self.inFile.read_ushort(3)
            
            self.create_face(meshName, i)
            self.add_face_verts(meshName, i, [v1, v2, v3])
        
    def parse_vertices(self, numVerts, meshName):
        
        for i in xrange(numVerts):
            vx, vy, vz = self.inFile.read_float(3)
            self.create_vertex(meshName, i)
            self.add_coords(meshName, i, [vx, vy, vz])        
        
        for i in xrange(numVerts):
            self.inFile.read_float(3)
            
        for i in xrange(numVerts):
            self.inFile.read_float(2)        
            
    def parse_materials(self, numMat):
        
        for i in range(numMat):
            self.inFile.seek(50, 1)
        
    def parse_file(self):
        '''Main parser method. Can be replaced'''
        
        magic = self.inFile.read_long()
        self.inFile.read_long()
        unk1 = self.inFile.read_long()
        lightingmap = self.inFile.read_long()
        unk3 = self.inFile.read_long()
        unk4 = self.inFile.read_long()
        unk5 = self.inFile.read_long()
        numMat = self.inFile.read_long()        
        
        if lightingmap:
            numMat += 1
        self.parse_materials(numMat)
        
        self.inFile.read_short()
        unk7, numVerts, numFaces = self.inFile.read_long(3)
        self.inFile.seek(20, 1)
        
        meshName = "obj"
        self.create_object(meshName)
        
        self.parse_vertices(numVerts, meshName)
        self.parse_faces(numFaces, meshName)
        
        
def read_file(path):
    '''Read the file'''
    
    openFile = StructReader(open(path, 'rb'))
    obj = AikaOnline_ms3(inFile=openFile)
    obj.parse_file()
    openFile.close()
    return obj

def write_file(path):
    
    pass

def definitions():
    '''Return the header, extension, and a description of the format'''
    
    return "\xAE\x08\x00\x00", "MS3", "Aika Online MS3"

if __name__ == '__main__':
    
    file1 = "giovN0011.MS3"
    read_file(file1)